package com.huangcy.gulimall.auth.component;

import com.alibaba.fastjson.JSONObject;
import com.huangcy.common.utils.HttpUtils;
import com.huangcy.gulimall.auth.client.GiteeHttpClient;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.UUID;

/**
 * @program: gulimall
 * @description:
 * @author: huangcy
 * @create: 2022-08-29 10:57
 **/
@Component
@ConfigurationProperties(prefix = "gitee.oauth")
public class GiteeComponent {
    /**
     * gitee授权中提供的 appid 和 appkey
     */
    @Value("${gitee.oauth.clientid}")
    private String clientId;
    @Value("${gitee.oauth.clientsecret}")
    private String clientSecret;
    @Value("${gitee.oauth.callback}")
    public String redirectUri;


    public String GiteeAuth(HttpSession session) {
        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        // Step1：获取Authorization Code
        String url = "https://gitee.com/oauth/authorize?response_type=code" +
                "&client_id=" + clientId +
                "&redirect_uri=" + URLEncoder.encode(redirectUri) +
                "&state=" + uuid +
                "&scope=user_info";

        //重定向
        return "redirect:" + url;
    }


    public String giteeCallback(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        // 得到Authorization Code
        String code = request.getParameter("code");

        // Step2：通过Authorization Code获取Access Token
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&client_id=" + clientId +
                "&client_secret=" + clientSecret +
                "&code=" + code +
                "&redirect_uri=" + redirectUri;
        JSONObject accessTokenJson = GiteeHttpClient.getAccessToken(url);

        if (url != null) {
            // Step3: 获取用户信息
            url = "https://gitee.com/api/v5/user?access_token=" + accessTokenJson.get("access_token");

            JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);

            JSONObject id = jsonObject.getJSONObject("id");

            JSONObject responseJson = new JSONObject();
            responseJson.put("id", id);
            return responseJson.toString();
        }

        /**
         * 获取到用户信息之后，就该写你自己的业务逻辑了
         */
        return "redirect:http://gulimall.com";
    }

}
